/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package UDP;
import java.io.*;
import java.net.*;
import java.nio.ByteBuffer;

/**
 *
 * @author QuangHau
 */
public class Client {
    public static void main(String[] args) {
        // TODO code application logic here
        // Client Program
        try{
           
            //khoi tao socket
            DatagramSocket socket =new DatagramSocket();
            int port = 1234;
            //Gan dia chi IP va port vao InetAddress
            //InetAddress ipServer= InetAddress.getByName("localhost");
            InetAddress ipServer = InetAddress.getByAddress("127.0.0.1", new byte[]{127, 0, 0, 1});
            
            /*----Tạo data----*/
            String stSend = "12347;1";
            byte []data = stSend.getBytes();
            
            /*----Tạo header-----*/
            byte []header = new byte[14];
            //type: tìm kiếm trunk
            header[0] = 10;
            //lenght
            short num = (short) (data.length);
            ByteBuffer dbuf = ByteBuffer.allocate(2);
            dbuf.putShort(num);
            byte[] lenght = dbuf.array();
            System.arraycopy(lenght,0,header,2,2);
            
            /*----Tạo gói tin-----*/
            byte[] sendData = new byte[1024];
            //gắn header
            System.arraycopy(header,0,sendData,0,14);
            //gắn data
            System.arraycopy(data,0,sendData,14,data.length);
            
            /*----gửi-----*/
            //Khoi tao DatagramPacket
            DatagramPacket sendPacket = new DatagramPacket(sendData,sendData.length,ipServer,port);
            //Send DatagramPacket
            for(int i=0; i< 2; i++)
            {
                socket.send(sendPacket);
            }
            //dong DatagramSocket
            socket.close();
            
            for(int i=0; i< sendData.length; i++)
            {
                System.out.print(sendData[i] + " ");
            }
            
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
}
